package cn.hqc.system.service.impl;


import cn.hqc.basic.service.impl.BaseServiceImpl;
import cn.hqc.system.domain.Menu;
import cn.hqc.system.service.IMenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-05-11
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    /**
     * 菜单树
     *
     * @return
     */
    @Override
    public List<Menu> tree() {
        List<Menu> result = new ArrayList<>();
        // 查询出来所有
        List<Menu> allMenu = this.findAll();
        // 转成map key id value menu
        Map<Long, Menu> menuMap = allMenu.stream().collect(Collectors.toMap(Menu::getId, m -> m));
        // 遍历集合
        allMenu.forEach(mu -> {
            if (null == mu.getParentId()) {
                result.add(mu);
            } else {
                Menu parent = menuMap.get(mu.getParentId());
                parent.getChildren().add(mu);
            }
        });
        return result;
    }
}
